package com.yugao.fintech.draper.tenant.service;

import com.yugao.fintech.draper.auth.api.TenantFeignApi;
import com.yugao.fintech.draper.core.exception.BaseException;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 租户信息合法性校验
 */
public class TenantValidService {

	private final LoadingCache<Long, BaseException> validTenantCache;

	private static final BaseException SERVICE_EXCEPTION_NULL = new BaseException("无异常信息");

	public TenantValidService(TenantFeignApi tenantFeignApi) {
		this.validTenantCache = Caffeine.newBuilder()
			.expireAfterAccess(1, TimeUnit.MINUTES)
			.expireAfterWrite(1, TimeUnit.MINUTES)
			.build(id -> {
				try {
					tenantFeignApi.validTenant(id);
					return SERVICE_EXCEPTION_NULL;
				}
				catch (BaseException e) {
					return e;
				}
			});
	}

	public void validTenant(Long id) {
		BaseException serviceException = validTenantCache.get(id);
		if (!Objects.equals(serviceException, SERVICE_EXCEPTION_NULL) && Objects.nonNull(serviceException)) {
			throw serviceException;
		}
	}
}
